package cn.ojh.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.ojh.domain.WechatButton;
import cn.ojh.service.IWechatButtonService;
import cn.ojh.vo.JSONMessage;

@Controller
@RequestMapping(value="/wechatButtons")
public class WeChatButtonController {

	@Autowired
	private IWechatButtonService wechatButtonService;
	
	/**
	 * 获取所有微信菜单按钮
	 */
	@RequestMapping(value="/getAll")
	@ResponseBody
	public List<WechatButton> getAll(){
		List<WechatButton> wechatButtonList = wechatButtonService.getAll();
		return wechatButtonList;
	}
	
	/**
	 * 进入微信菜单按钮管理界面
	 */
	@RequestMapping(value="/view")
	public String view(Model model) {
		//获取所有菜单按钮数据（作用域）
		List<WechatButton> wechatButtonList = wechatButtonService.getAll();
		model.addAttribute("buttonTree", JSON.toJSONString(wechatButtonList));
		return "button/button";
	}
	
	
	/**
	 *通过菜单按钮的ID获取该按钮的子按钮
	 */
	@RequestMapping(value="/{buttonId}/childs")
	public String getChildButton(@PathVariable("buttonId") Long buttonId,Model model) {
		List<WechatButton> childButtonList = wechatButtonService.getChildButtonList(buttonId);
		model.addAttribute("childButtonList",childButtonList);
		return "button/child_button";
	}
	
	/**
	 * 新增或修改菜单按钮
	 */
	@RequestMapping(value="",method=RequestMethod.POST)
	@ResponseBody
	public JSONMessage save(WechatButton wechatButton) {
		JSONMessage jSONMessage =new JSONMessage();
		try {
			wechatButtonService.save(wechatButton);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jSONMessage.setErrmsg(e.getMessage());
		}
		return jSONMessage;
	}
	
	/**
	 * 通过主键id删除对应的数据
	 */
	@RequestMapping(value="/{id}")
	@ResponseBody
	public JSONMessage delete(@PathVariable("id")Long id){
		JSONMessage jSONMessage =new JSONMessage();
		try {
			wechatButtonService.delete(id);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jSONMessage.setErrmsg(e.getMessage());
		}
		return jSONMessage;
	}
	
	/**
	 * 更新菜单按钮到微信公众号
	 */
	@RequestMapping(value="/publish")
	@ResponseBody
	public JSONMessage updateButton() {
		JSONMessage jSONMessage =new JSONMessage();
		try {
			wechatButtonService.updateButton();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jSONMessage.setErrmsg(e.getMessage());
		}
		return jSONMessage;
	}
}









